package com.coderg.gmall.cart.filter;

import com.alibaba.fastjson.JSONObject;
import com.coderg.gmall.cart.util.GmallThreadLocalUtils;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Base64;

/**
 * @Description
 * @Author CoderG
 * @Date 2025/6/6 0:17
 **/
@WebFilter(filterName = "cartFilter",urlPatterns = "/*")
@Order(1)
public class CartFilter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //获取请求头的token 解析出用户名 放入ThreadLocal
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String token = httpServletRequest.getHeader("Authorization").replace("Bearer ","");
        String payload= token.split("\\.")[1];
        String date = new String(Base64.getDecoder().decode(payload));

        String username = (String) JSONObject.parseObject(date).get("username");
        GmallThreadLocalUtils.setUserName(username);
        // 放行
        filterChain.doFilter(servletRequest, servletResponse);
    }

}
